<?php

namespace App\Models;

//use App\Api\Helpers\Services\GradeService;
use Carbon\Carbon;
//use Encore\Admin\Auth\Database\Role;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Laravel\Passport\HasApiTokens;


class User extends Authenticatable
{
    use Notifiable,HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = 'user';
//    protected $primaryKey = 'user_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'nickname',
        'password',
        'reg_time',
        'ys_coin',
        'regId',
        'role',
        'head',
        'sex',
        'birthday',
        'signature'
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];



    public function scopeToday($query)
    {

        $y = date("Y");

        $m = date("m");

        $d = date("d");
        $todayTime= mktime(0,0,0,$m,$d,$y);

        return $query->where('register_time', '>', $todayTime);
    }

    //用户能否有余额赠送
    public function canSendGift(Gift $gift,$count=1){


        if ($gift->id == 1){

            return $this->flowers >= $count;
        }

        return $this->ys_coin >= $gift->price * $count;

    }

    // 用户收到的所有礼物
    public function gifts(){
        return $this->hasMany(GivedGift::class,'gifts_uid','id');

    }

    // 用户送出的礼物记录
    public function sendGifts(){
        return $this->hasMany(GivedGift::class,'uid','id');
    }


    // 一个用户有多吧个申请
    public function barApply(){
        return $this->belongsToMany(User::class,'bar_applies','apply_uid','author_id');
    }

    // 一个作者有多个用户催促开通吧
    public function barApplyed(){
        return $this->belongsToMany(User::class,'bar_applies','author_id','apply_uid');

    }

    // 一个用户可以发布多条帖子
    public function posts(){

        return $this->hasMany(Post::class,'uid','id');

    }

    // 一个用户有多条消费记录
    public function recharges(){

        return $this->hasMany(Recharge::class,'uid','id');

    }


    // 一个用户有多个书单
    public function bookCollection(){
        return $this->hasMany(BookCollection::class);

    }


    // 用户自己的bar
    public function bars(){
        return $this->hasMany(Bar::class,'uid','id');
    }

    public function isReply(User $author){

        $record = DB::table('bar_applies')
            ->where([
                'apply_uid' => $this->id,
                'author_id' => $author->id

            ])
            ->orderBy('created_at','desc')
            ->first();

        if (!empty($record)  || !empty($record->created_at) ){

            $isToday = Carbon::parse($record->created_at)->isToday();

            if ($isToday){
                return true;
            }
        }

        return false;


    }


    public function fans(){

        return $this->hasMany(UserFans::class,'uid','id');

    }

    public function following(){

        return $this->belongsToMany(User::class,'userfans','fans_id','uid');

//        return $this->hasMany(UserFans::class,'fans_id','id');

    }

    public function books(){

        return $this->hasMany(Book::class,'uid','id');

    }


    // 用户编辑帖子的权限
    public function canSetPosts($permission,Post $post){

        $bar = $post->bar;

        if (empty($bar)){
            return false;
        }


        $roles = $this->roles()
            ->where('bar_id',$bar->id)
            ->get();

        foreach ($roles as $role){

            $permissions = $role->permissions()->pluck('slug')->toArray();

            if (in_array($permission,$permissions)){
                return true;

            }
        }

        return false;

    }

    // 用户编辑评论的权限
    public function canSetComments($permission,Comment $comment){

        $post = $comment->post;

        if (empty($post)){

            return false;

        }

        $bar = $post->bar;

        if (empty($bar)){
            return false;
        }

        $roles = $this->roles()
            ->where('bar_id',$bar->id)
            ->get();

        foreach ($roles as $role){

            $permissions = $role->permissions()->pluck('slug')->toArray();

            if (in_array($permission,$permissions)){
                return true;

            }
        }

        return false;

    }



    public function getAuthPassword()
    {

//        dd('in');

        return $this->pwd;

        return $this->password;
    }


    // 一个用户有多个吧权限
    public function barRoles(){
        return $this->hasMany(BarRoleUser::class);
    }

    public function roles(){

        return $this->belongsToMany(BarRole::class,'bar_role_users','user_id','role_id')->withTimestamps();

    }


    // 给当前用户添加吧的权限
    public function attachBarRole($role,$bar){

        $this->roles()->attach($role->id,['bar_id' => $bar->id]);

    }




    // 用户喜欢的帖子
    public function likedPosts(){
        return $this->hasMany(PostsLikes::class,'uid','id');
    }

    public function isLikePost(Post $post){


        return !! $this->likedPosts()->where([
            'status' => 0,
            'posts_id' => $post->id
        ])->count();

    }

    public function likePost($post){

        $like_post = $this->likedPosts()->firstOrCreate([
            'posts_id' => $post->id
        ]);

        $like_post->likes_time = time();
        $like_post->status = 0;

        $like_post->save();

        return $like_post;

    }

    public function unlikePost($post){
        $like_post = $this->likedPosts()->where('posts_id',$post->id)->first();

        $like_post->status = 1;

        $like_post->likes_time = time();
        $like_post->save();
        return $like_post;

    }



//
//    public function getUserGradeAttribute(){
//
//
//        $exp = $this->attributes['grade'];
//
//        $grade_service = new GradeService();
//        return $grade_service->convertGrade($exp);
//
//    }


    public function readRecord(){

        return $this->hasMany(ReadRecord::class,'uid','id');

    }



    // 用户书架的所有书籍
    public function shelf(){

        return $this->belongsToMany(Book::class,'bookshelf','uid','book_num')
            ->wherePivot('status',0);

    }


    protected static function boot()
    {
        parent::boot();

        static::updating(function ($user) {

            if ($user->flowers > 10){

                $user->flowers = 10;

            }

        });

    }




    public function findForPassport($username) {
        return $this->where('phone', $username)->first();
    }



    // 重写setRememberToken，方式rememberToken的时候报错
    public function setRememberToken($value)
    {

    }

}
